<template>
  <el-card>
    <el-tabs
        v-model="configGroupMark"
        tab-position="left"
        @tab-click="handleClick"
    >

      <el-tab-pane name="add" disabled>
        <template #label>
          <el-button type="primary" icon="plus" @click.stop="handleAddConfigGroup(true)">新增配置分组</el-button>
        </template>
      </el-tab-pane>
      <el-tab-pane
          v-for="item in groupList"
          :key="item.id"
          :label="item.name"
          :name="item.mark"
      >
        <template #label>
          <div>
            <span>{{ item.name }}</span>
            <el-space :size="0">
              <el-button type="primary" icon="edit" link @click.stop="handleAddConfigGroup(false, item)"></el-button>
              <el-button type="danger" icon="delete" link @click.stop="handleDelete(item)"></el-button>
            </el-space>
          </div>
        </template>
        <div class="flex items-center justify-between border-b mb-2.5">
          <span>{{ item.name }}：({{ item.mark }})</span>
          <el-button type="primary" icon="setting" circle @click="handleSetting"></el-button>
        </div>
        <ConfigFrom :form-config="formConfig"></ConfigFrom>
      </el-tab-pane>
    </el-tabs>
    <!-- 新增配置分组表单 -->
    <el-dialog
      v-model="configGroupShow"
      :title="dialogTitle"
      width="500"
    >
      <el-form ref="configGroupRef" :model="configGroupForm" :rules="configGroupRules" label-position="right" label-width="auto">
        <el-form-item label="分组名称" prop="name">
          <el-input v-model="configGroupForm.name" />
        </el-form-item>
        <el-form-item label="分组标识" prop="mark">
          <el-input v-model="configGroupForm.mark" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="configGroupForm.sort" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseConfigGroup">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!--  配置表格  -->
    <ConfigTable :visible="tableShow" :group_id="groupId" @close="tableShow = false" />
  </el-card>
</template>

<script lang="ts" setup>
import {ref, onMounted, computed, nextTick, reactive} from 'vue'
import {
  getConfigGroupListApi,
  getConfigGroupInfoApi,
  deleteConfigGroupInfoApi,
  updateConfigGroupInfoApi, saveConfigGroupInfoApi
} from '@/api/sysConfigGroup'
import {
  getConfigFormListApi
} from '@/api/sysConfig'
import {ElMessage, ElMessageBox, TabsPaneContext, type FormInstance, type FormRules} from 'element-plus'
import ConfigFrom from './configForm.vue'
import ConfigTable from './configTable.vue'

// 从后端获取的表单配置
const formConfig = ref([]);
// 响应式数据
const groupList = ref([]); // 分组列表

const groupId = ref(null);

// 配置分组弹框
const configGroupShow = ref(false);

// 对话框标题
const dialogTitle = computed(() => (isAdd.value ? '新增配置分组' : '编辑配置分组'));

// 是否新增
const isAdd = ref(false);

// 表单实例
const configGroupRef = ref<FormInstance>();

interface ConfigGroupForm {
  name: string;
  mark: string;
  sort: number;
  id?: number; // 添加可选的 id 字段
}

const initConfigGroupForm = reactive<ConfigGroupForm>({
  name: '',
  mark: '',
  sort: 1,
});

const configGroupForm = reactive<ConfigGroupForm>({
  name: '',
  mark: '',
  sort: 1,
});

// 当前配置分组ID
const configGroupMark = ref<string | number>('');

const configGroupRules = ref<FormRules<ConfigGroupForm>>({
  name: [
    { required: true, message: '配置分组名称必填', trigger: 'change' },
  ],
  mark: [
    { required: true, message: '配置分组标识必填', trigger: 'change' },
  ],
});

// 显示配置表格
const tableShow = ref(false);

// 设置配置表格事件
const handleSetting = () => {
  tableShow.value = true
}

// 打开新增配置分组表单弹框
const handleAddConfigGroup = async (isNew: boolean, row?: { id: number }) => {
  configGroupShow.value = true;
  isAdd.value = isNew;

  // 重置表单：合并初始值到响应式对象
  Object.assign(configGroupForm, initConfigGroupForm);
  await nextTick(() => {
    configGroupRef.value?.clearValidate();
    configGroupRef.value?.resetFields();
  });
  // 编辑模式：加载数据
  if (!isAdd.value && row?.id) {
    const response = await getConfigGroupInfoApi(row.id);
    // 合并接口数据到响应式对象
    Object.assign(configGroupForm, response.data);
  }
};

// 关闭新增配置分组表单弹框
const handleCloseConfigGroup = () => {
  configGroupShow.value = false;
}

// 删除配置分组
const handleDelete = (row) => {
  ElMessageBox.confirm(
      '确定删除此数据吗?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then( async () => {
    // 执行删除操作
    await deleteConfigGroupInfoApi(row.id);
    // 刷新数据
    await handleConfigGroupList();
    // 提示删除成功
    ElMessage({
      type: 'success',
      message: '删除成功',
    });
  })
};

// 提交配置分组表单
const handleSubmit = async () => {
  if (!configGroupRef.value) return;

  // 校验表单
  await configGroupRef.value.validate();

  // 判断是否为新增或更新
  const isUpdate = !!configGroupForm.id; // 如果存在 id，则为更新操作

  // 执行新增或更新操作
  if (isUpdate) {
    // 更新操作
    await updateConfigGroupInfoApi(configGroupForm.id, configGroupForm);
    ElMessage.success('更新成功');
  } else {
    // 新增操作
    await saveConfigGroupInfoApi(configGroupForm);
    ElMessage.success('新增成功');
  }

  // 关闭对话框并刷新数据
  handleCloseConfigGroup();
  await handleConfigGroupList();
};

// tag配置分组选中
const handleClick = (tab: TabsPaneContext) => {
  configGroupMark.value = tab.props.name
  getConfigForm()
}

// 获取配置表单
const getConfigForm = async () => {
  const response = await getConfigFormListApi({ mark: configGroupMark.value });
  formConfig.value = response.data.configs;
  groupId.value = response.data.id
}

// 获取配置分组列表
const handleConfigGroupList = async () => {
  const response = await getConfigGroupListApi()
  groupList.value = response.data
  configGroupMark.value = response.data[0].mark
  await getConfigForm()
}

onMounted(() => {
  handleConfigGroupList()
})
</script>

<style>

</style>
